import {createRouter, createWebHistory} from "vue-router";
import TablePage from "./components/table-page.vue";
import EmptyPage from "./components/empty-page.vue";
import NotFound from "./pages/not-found.vue";
import config from "./config.js";
import pages from "./pages";

const pageIndex = pages.reduce((index, page) => {
  index[page.key] = page;
  return index;
}, {});

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      component: () => import("./pages/login.vue"),
      meta: {
        title: '登录'
      }
    },
    {
      path: '/login/wx-open',
      component: () => import("./pages/wx-open-login.vue"),
      meta: {
        title: '登录',
        progress: false
      }
    },
    {
      path: '/',
      // redirect: '/home',
      component: () => import("./pages/main-layout.vue"),
      children: [
        ...config.menus.flatMap(menu => {
          if (menu.pages == null) {
            const page = pageIndex[menu.key];
            return [
              {
                path: menu.key,
                meta: {
                  title: menu.text
                },
                component: page.config.component
              }
            ];
          }
          return menu.pages.map(key => {
            const page = pageIndex[key];
            if (page == null) {
              console.error(`页面不存在：${key}`);
              return null;
            }
            return {
              path: page.key,
              meta: {
                title: page.title
              },
              component: page.type === 'table' ? {
                components: {TablePage},
                render() {
                  return <table-page config={page.config}/>;
                }
              } : page.type === 'empty' ? {
                components: {EmptyPage},
                render() {
                  return <empty-page config={page.config}/>;
                }
              } : page.config.component
            };
          });
        }).filter(Boolean),
        {
          path: '/:pathMatch(.*)*',
          component: NotFound
        }
      ]
    }
  ]
});

router.beforeEach((to) => {
  document.title = to.meta.title == null ? import.meta.env.VITE_TITLE
    : `${to.meta.title} · ${import.meta.env.VITE_TITLE}`;
});
export default router;
